package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.Excel.ExcelData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.Myexception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class ExcelListener extends AnalysisEventListener<ExcelData> {
    private EduSubjectService eduSubjectService;
    public ExcelListener(){}
    public ExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(ExcelData data, AnalysisContext context) {
        if(data==null){
            throw new GuliException();
        }
        EduSubject oneSub = isOneSub(data.getOneSubject());
//        说明数据库中没有  直接添加到数据库中
        if(oneSub==null){
            EduSubject eduSubject = new EduSubject();
            eduSubject.setParentId("0");
            eduSubject.setTitle(data.getOneSubject());
            eduSubjectService.save(eduSubject);
        }
        EduSubject twoSub = isTwoSub(data.getTwoSubject(), oneSub.getId());
        if(twoSub==null){
            EduSubject eduSubject = new EduSubject();
            eduSubject.setParentId(oneSub.getId());
            eduSubject.setTitle(data.getTwoSubject());
            eduSubjectService.save(eduSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
    //    判断父目录是否存在数据库中
    public EduSubject isOneSub(String name){
        QueryWrapper<EduSubject> eduSubjectQueryWrapper = new QueryWrapper<>();
//        判断数据库中是否有该父类型分类
        eduSubjectQueryWrapper.eq("title",name);
        eduSubjectQueryWrapper.eq("parent_id","0");
        EduSubject one = this.eduSubjectService.getOne(eduSubjectQueryWrapper);
        return one;
    }
    //    判断二级目录是否存在数据库中
    public EduSubject isTwoSub(String name,String parent_id){
        QueryWrapper<EduSubject> eduSubjectQueryWrapper = new QueryWrapper<>();
//        判断数据库中是否有该父类型分类
        eduSubjectQueryWrapper.eq("title",name);
        eduSubjectQueryWrapper.eq("parent_id",parent_id);
        EduSubject two = this.eduSubjectService.getOne(eduSubjectQueryWrapper);
        return two;
    }
}
